import { createRouter, createWebHistory } from 'vue-router'
import * as jwtDecode from 'jwt-decode';
//服务请求响应组件导入
import _102View from "@/components/service/102View.vue"
import _403View from "@/components/service/403View.vue"
import _404View from "@/components/service/404View.vue"
import _500View from "@/components/service/500View.vue"
//系统功能组件导入
import HomeView from '@/views/system/HomeView.vue'
import LoginView from "@/views/system/LoginView.vue";
import RegisterView from "@/views/system/RegisterView.vue";
import ForgetView from "@/views/system/ForgetView.vue";
//用户功能组件导入
import LearningView from "@/views/student/learn/LearningView.vue";
import CurriculumView from "@/views/student/learn/CurriculumView.vue";
import KonwledgeBaseView from "@/views/student/learn/KonwledgeBaseView.vue";
import ForumView from "@/views/student/learn/ForumView.vue";
import ModelView from "@/views/student/learn/ModelView.vue";
import OneModelView from "@/views/student/learn/OneModelView.vue";
import NoteView from "@/views/student/note/NoteView.vue";
import CourseNoteView from "@/views/student/note/CourseNoteView.vue";
import PersonalNoteView from "@/views/student/note/PersonalNoteView.vue";
import UserInfoView from "@/views/student/personal/UserInfoView.vue";
import ShowNoteView from "@/views/student/note/ShowNoteView.vue";
import ShowCollextView from "@/views/student/note/ShowCollextView.vue";
//用户编辑器公共组件导入
import readEditor from "@/components/communal/read-communal.vue";
import writeEditor from "@/components/communal/write-communal.vue";
//管理员界面
import LoginAdmin from "@/views/system/LoginAdminView.vue";
import CourseManege from "@/views/admin/courseManege/CourseManegeView.vue";
import CourseInfoView from "@/views/admin/courseManege/CourseInfoView.vue";
import AddCourseView from "@/views/admin/courseManege/AddCourseView.vue";
import UsersManegeView from "@/views/admin/userManege/UsersManegeView.vue";
import AccountBannedView from "@/views/admin/userManege/AccountBannedView.vue";
import ProhibitionRecordsView from "@/views/admin/userManege/ProhibitionRecordsView.vue";
import ArticleReviewView from "@/views/admin/articleReview/ArticleReviewView.vue";
import AricleInspectView from "@/views/admin/articleReview/AricleInspectView.vue";
//其他界面组件导入
import TeamView from "@/views/other/TeamView.vue";

//导入ad
import ad from  "@/components/ad/ad.vue"
import ReadCommunal from "@/components/communal/read-communal.vue";
const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: [
    {
      path: '/',
      name: 'main',
      redirect:'/home'
    },
    {
      path : '/home/sjm',
      name : 'sjm',
      component : ''
    },
    {
      path: '/home',
      name: 'home',
      component: HomeView
    },
    {
      path:'/login',
      name:'login',
      component:LoginView
    },
    {
      path: '/admin/login',
      name: 'admin/login',
      component: LoginAdmin
    },
    {
      path:'/forgot',
      name:'forgot',
      redirect: '/102'
    },
    {
      path:'/register',
      name:'register',
      component:RegisterView
    },
    {
      path:'/student',
      name:'student',
      redirect: '/std/learn',
      meta: {requiresAuth: true, roles: ['student']},
      children:[
        {
          path:'/std/learn',
          name:'std/learn',
          component:LearningView,
          meta: {requiresAuth: true, roles: ['student']}
        },
        {
          path:'/std/curriculum',
          name:'std/curriculum',
          component:CurriculumView,
          meta: {requiresAuth: true, roles: ['student']}
        },
        {
          path:'/std/curriculum/library',
          name:'std/curriculum/library',
          component:KonwledgeBaseView,
          meta: {requiresAuth: true, roles: ['student']}
        },
        {
          path: '/std/curriculum/show',
          name: 'std/curriculum/show',
          component: readEditor,
          meta: {requiresAuth: true, roles: ['student']}
        },
        {
          path:'/std/model',
          name:'std/model',
          component: ModelView,
          meta: {requiresAuth: true, roles: ['student']}
        },
        {
          path:'/std/model/specific',
          name:'std/model/specific',
          component: OneModelView,
          meta: {requiresAuth: true, roles: ['student']}
        },
        {
          path:'/std/forum',
          name:'std/forum',
          component:ForumView,
          meta: {requiresAuth: true, roles: ['student']}
        },
        {
          path: '/std/forum/show',
          name: 'std/forum/show',
          component: readEditor,
          meta: {requiresAuth: true, roles: ['student']}
        },
        {
          path: '/std/forum/write',
          name: 'std/forum/write',
          component: writeEditor,
          meta: {requiresAuth: true, roles: ['student']}
        },
        {
          path:'/std/note',
          name:'std/note',
          component: NoteView,
          meta: {requiresAuth: true, roles: ['student']}
        },
        {
          path: '/std/note/persona',
          name:'std/note/persona',
          component:PersonalNoteView,
          meta: {requiresAuth: true, roles: ['student']}
        },
        {
          path: '/std/note/course',
          name:'std/note/course',
          component:CourseNoteView,
          meta: {requiresAuth: true, roles: ['student']}
        },
        {
          path: '/std/note/show',
          name:'std/note/show',
          component:readEditor,
          meta: {requiresAuth: true, roles: ['student']}
        },
        {
          path: '/std/note/show/collect',
          name:'std/note/show/collect',
          component:ShowCollextView,
          meta: {requiresAuth: true, roles: ['student']}
        },
        {
          path: '/std/note/write',
          name:'std/note/write',
          component:writeEditor,
          meta: {requiresAuth: true, roles: ['student']}
        },
        {
          path:'/std/userInfo',
          name:'std/userInfo',
          component:UserInfoView,
          meta: {requiresAuth: true, roles: ['student']}
        }
      ]
    },
    {
      path: '/admin',
      name: 'admin',
      redirect: 'admin/course',
      meta: {requiresAuth: true, roles: ['admin']},
      children:[
        {
          path: '/admin/course',
          name: 'admin/course',
          component: CourseManege,
          meta: {requiresAuth: true, roles: ['admin']}
        },
        {
          path: '/admin/course/info',
          name: 'admin/course/info',
          component: CourseInfoView,
          meta: {requiresAuth: true, roles: ['admin']}
        },
        {
          path: '/admin/course/add',
          name: 'admin/course/add',
          component: AddCourseView,
          meta: {requiresAuth: true, roles: ['admin']}
        },
        {
          path: '/admin/users',
          name: 'admin/users',
          component: UsersManegeView,
          meta: {requiresAuth: true, roles: ['admin']}
        },
        {
          path: '/admin/users/ban',
          name: 'admin/users/ban',
          component: AccountBannedView,
          meta: {requiresAuth: true, roles: ['admin']}
        },
        {
          path: '/admin/users/record',
          name: 'admin/users/record',
          component: ProhibitionRecordsView,
          meta: {requiresAuth: true, roles: ['admin']}
        },
        {
          path: '/admin/article',
          name: 'admin/article',
          component: ArticleReviewView,
          meta: {requiresAuth: true, roles: ['admin']}
        },
        {
          path: '/admin/inspect',
          name: 'admin/inspect',
          component: ReadCommunal,
          meta: {requiresAuth: true, roles: ['admin']}
        }
      ]
    },
    {
      path: '/other',
      name: 'other',
      redirect:'/teams',
      children:[
        {
          path: '/teams',
          name: 'teams',
          component: TeamView}
      ]
    },
    {
      path:'/102',
      name:'102',
      component:_102View
    },
    {
      path:'/403',
      name:'403',
      component:_403View
    },
    {
      path:'/404',
      name:'404',
      component:_404View
    },
    {
      path:'/500',
      name:'500',
      component:_500View
    },
  ]
})
router.beforeEach((to, from, next) => {
  //如果用户不存在，则无法访问需要登录的页面
  const userStr = JSON.parse(sessionStorage.getItem('user'))
  if(to.meta.requiresAuth && userStr){
    userStr.role=userStr.role?'admin':'student'
  }
  //登录就有token
  const tokenStr = sessionStorage.getItem("Authorization")
  // console.log(tokenStr)
  //用户身份
  const userRule = ''
  //检查是否需要验证
  if (to.matched.some(record => record.meta.requiresAuth)){
    //需要验证，但是没有token，表示未登录
    if(!tokenStr) {
      $message.destroyAll()
      $message.error("- 请先登录 -")
      next(from.path)
    } else if(to.matched.some(record => record.meta.roles)){
      //检查用户是否符合满足路由的要求
      const hasRole = to.matched.some(record => {
        // console.log("record.meta.roles=>>"+record.meta.roles.some(role => userStr.rule.includes(role)))
        return record.meta.roles.some(role => userStr.role.includes(role));
      })
      if(hasRole) {
        next()
      }else {
        //角色权限不足
        next('/403')
      }
    }else {
      //不需要特定角色，允许访问
      next()
    }
  }else {
    //路由不需要验证，允许访问
    if(to.matched.length===0){
      next('/404')
    }
    next()
  }
})
// //将不同权限访问页面进行分流处理
// let studentRoutes = []  //登录用户访问路由
// let adminRoutes = []    //管理员路由
// let serverRoutes = []   //服务响应路由
// let otherRoures = []
// router.getRoutes().forEach((rt)=>{
//   if (rt.name.slice(0,3)==='std'){
//     //设置登录用户路由，以std开始
//     studentRoutes.push(rt.name)
//   } else if(rt.name.slice(0,1) === '_'){
//     otherRoures.push(rt.name)
//   } else {
//     //设置响应服务路由，无指定字符串起始
//     serverRoutes.push(rt.name)
//   }
// })
// //对路由进行校验
// function routerFilter(paths=[],name) {
//   let action = false;
//   paths.forEach((path) => {
//     if (name === path) {
//       action = true
//     }
//   })
//   return action
// }
// router.beforeEach((to,from,next) => {
//   //如果用户不存在，则无法访问需要登录的页面
//   const screenStr = JSON.parse(sessionStorage.getItem('user'))
//   if(routerFilter(studentRoutes,to.name) && !screenStr){
//     $message.destroyAll()
//     $message.error("- 请先登录 -")
//     return next(from.path)
//   }
//   if(routerFilter(studentRoutes,to.name) && screenStr) return next()
//   if (routerFilter(serverRoutes,to.name)) return next()
//   return next('/')
// })

export default router
